import math
from decimal import Decimal


def get_valid_input(prompt, input_type=int, min_val=None, max_val=None):
    """获取并验证用户输入的合法值"""
    while True:
        try:
            value = input_type(input(prompt))
            if min_val is not None and value < min_val:
                print(f"输入值必须 ≥ {min_val}")
                continue
            if max_val is not None and value > max_val:
                print(f"输入值必须 ≤ {max_val}")
                continue
            return value
        except ValueError:
            print("输入无效，请重新输入。")


def calculate_min_draws(total, target, probability):
    """计算达到目标概率所需的最小抽牌数"""
    if probability <= 0:
        return 1
    if target == 0:
        return None

    prob_decimal = Decimal(str(probability))

    for draw_num in range(1, total + 1):
        # 当非目标牌不足时概率自动为100%
        if (total - target) < draw_num:
            return draw_num

        # 计算组合数
        non_target_comb = math.comb(total - target, draw_num)
        total_comb = math.comb(total, draw_num)

        # 计算精确概率
        exact_prob = Decimal(1) - Decimal(non_target_comb) / Decimal(total_comb)

        if exact_prob >= prob_decimal - Decimal('1e-10'):
            return draw_num

    return None


def main():
    print("=== 抽牌概率计算器 ===")
    print("参数说明：")
    print("- 剩余牌数：牌堆当前总牌数（≥1）")
    print("- 目标牌数：您希望抽中的牌数量（0~剩余牌数）")
    print("- 期望概率：期望达到的最小概率（0~1）\n")

    total = get_valid_input("请输入剩余牌数：", int, 1)
    target = get_valid_input("请输入目标牌数：", int, 0, total)
    probability = get_valid_input("请输入期望概率：", float, 0.0, 1.0)

    result = calculate_min_draws(total, target, probability)

    print("\n计算结果：")
    if result is None:
        print("无法达到目标概率（可能原因：目标牌数为0且要求概率＞0）")
    else:
        print(f"需要至少抽取 {result} 张牌")
        actual_prob = 1 - math.comb(total - target, result) / math.comb(total, result)
        print(f"实际概率：{actual_prob:.4%}（误差＜0.0001%）")


if __name__ == "__main__":
    main()
